package com.idrem.views.login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml.Encoding;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.idrem.IdremApplication;
import com.idrem.R;
import com.idrem.asynctask.BaseAsyncTask;
import com.idrem.asynctask.BaseAsyncTask.TaskOnPostExecuteListener;
import com.idrem.asynctask.BaseAsyncTask.TaskResult;
import com.idrem.asynctask.LoginTask;
import com.idrem.common.Common;
import com.idrem.data.model.Response;
import com.idrem.data.model.User;
import com.idrem.views.home.HomeAct;
import com.idrem.views.home.HomeActivity;

public class LoginActivity extends Activity {

	private static final String TAG = "LoginActivity";
	private IdremApplication application;
	public static LoginActivity instance = null;
	private AlertDialog dialog;
	private SharedPreferences myPreferences;
	private SharedPreferences.Editor localEditor;
	private CheckBox login_ckb_auto;
	private CheckBox login_ckb_savepwd;
	private EditText login_et_pwd;
	private EditText login_et_uid;

	private boolean showing = false;
	private Button btnSumbit;
	private Button btnSetting;
	private String usr = "", pwd = "", ip = "", port = "";
	private EditText loginsetting_ip = null;
	private EditText loginsetting_port = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.login);
		application = (IdremApplication) getApplication();

		this.btnSumbit = (Button) findViewById(R.id.login_btn_sumbit);
		this.btnSetting = (Button) findViewById(R.id.login_btn_setting);
		this.login_ckb_auto = ((CheckBox) findViewById(R.id.login_ckb_auto));
		this.login_ckb_savepwd = ((CheckBox) findViewById(R.id.login_ckb_savepwd));
		this.login_ckb_auto.setButtonDrawable(R.drawable.ucheckbox);
		this.login_ckb_savepwd.setButtonDrawable(R.drawable.ucheckbox);
		this.login_et_uid = ((EditText) findViewById(R.id.login_et_uid));
		this.login_et_pwd = ((EditText) findViewById(R.id.login_et_pwd));

		/**for test
		 * 贵阳平台的 xiaojiao.chen 123456 厦门平台的 ni.xie 123456 长沙平台的 huidong.li
		 * 123456
		 */
		login_et_uid.setText("xiaojiao.chen");
		login_et_pwd.setText("123456");

		usr = login_et_uid.getText().toString().trim();
		pwd = login_et_pwd.getText().toString().trim();

		MyListener listener = new MyListener();
		btnSumbit.setTag(1);
		btnSumbit.setOnClickListener(listener);
		btnSetting.setTag(2);
		btnSetting.setOnClickListener(listener);

		this.myPreferences = getSharedPreferences("UserInfo", 0);
		this.localEditor = this.myPreferences.edit();
		this.login_ckb_savepwd.setChecked(this.myPreferences.getBoolean("save", true));
		this.login_ckb_auto.setChecked(this.myPreferences.getBoolean("auto", true));

		if (this.login_ckb_savepwd.isChecked()) {
			this.login_et_uid.setText(this.myPreferences.getString("uid", ""));
			this.login_et_pwd.setText(this.myPreferences.getString("pwd", ""));
			if (this.myPreferences.getBoolean("auto", true)) {
				usr = this.myPreferences.getString("uid", "");
				pwd = this.myPreferences.getString("pwd", "");
				if ((usr != null) && (usr.length() > 0)) {
					if (Common.isNetworkAvailable(this))
						login(usr, pwd);
				}
			}
		}
		//for test
		usr = "xiaojiao.chen";
		pwd = "123456";
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if ((requestCode != 0) || (resultCode != -1))
			Toast.makeText(getApplicationContext(), data.getStringExtra("msg"), Toast.LENGTH_LONG).show();
	}

	/**
	 * Login task for getting login data.
	 * 
	 * @param count
	 * @param isMore
	 */
	private void startLoginTask(String user, String password) {
		// showProgressBar();
		LoginTask mTask = new LoginTask();
		mTask.setTaskOnPostExecuteListener(new TaskOnPostExecuteListener<Response>() {

			public void onPostExecute(TaskResult<? extends Response> result) {
				if (result != null && result.Status == BaseAsyncTask.STATUS_SUCCESS) {
					// dismissProgressBar();
					Response resp = result.Value;
					if (resp == null) {
						Toast.makeText(getApplicationContext(), "Server response is null", Toast.LENGTH_LONG).show();
						return;
					} else {
						String msg = resp.getMessage();
						if (msg.startsWith("OK")) {
							String[] userinfo = msg.split(",");
							int len = userinfo.length;
							String usrNm = userinfo[len - 1].substring(0);
							Intent intent=new Intent();
				            intent.putExtra("user", usrNm);
				            intent.setClass(LoginActivity.this, HomeAct.class);
				            LoginActivity.this.startActivity(intent);
							startActivity(intent);
						}
					}
				}
			}
		});
		mTask.execute("login", new User(user, password).toString());
	}

	public class MyListener implements View.OnClickListener {

		public void onClick(View v) {
			int tag = (Integer) v.getTag();
			switch (tag) {
			case 1:
				 login(usr, pwd);
//				saveUserConfig(usr, pwd);
//				String usrNm = getLoginResp(usr, pwd);
//	            Intent intent=new Intent();
//	            intent.putExtra("user", usrNm);
//	            intent.setClass(LoginActivity.this, HomeAct.class);
//	            LoginActivity.this.startActivity(intent);
				break;
			case 2:
				LayoutInflater factory = LayoutInflater.from(LoginActivity.this);
				final View textEntryView = factory.inflate(R.layout.loginsetting, null);
				final EditText editText1 = (EditText) textEntryView.findViewById(R.id.loginsetting_ip1);
				final EditText editText2 = (EditText) textEntryView.findViewById(R.id.loginsetting_port1);
				editText1.setText(myPreferences.getString("svrip", ""));
				editText2.setText(myPreferences.getString("svrport", ""));

				dialog = new AlertDialog.Builder(LoginActivity.this).setIcon(R.drawable.sync).setTitle(R.string.alert_dialog_login_setting_title).setView(textEntryView).setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// get ip and port info
						ip = editText1.getText().toString().toString().trim();
						port = editText2.getText().toString().toString().trim();
						if ((ip == null && ip.length() <= 0) || (port == null && port.length() <= 0)) {
							Toast.makeText(getApplicationContext(), "Please enter server IP and Port!", Toast.LENGTH_SHORT).show();
						} else {
							localEditor.putString("svrip", ip).commit();
							localEditor.putString("svrport", port).commit();
						}
					}
				}).setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// close this diablog
					}
				}).create();

				dialog.show();
				break;

			default:
				break;
			}
		}
	}

	/**
	 * login with user info
	 * 
	 */
	public void login(String usrStr, String pwdStr) {
		 saveUserConfig(usrStr, pwdStr);
		 startLoginTask(usrStr,pwdStr);
		}

	/**
	 * save User data.
	 * 
	 */
	public void saveUserConfig(String usrStr, String pwdStr) {
		if (this.login_ckb_savepwd.isChecked()) {
			this.localEditor.putString("uid", usrStr).commit();
			this.localEditor.putString("pwd", pwdStr).commit();
			this.localEditor.putBoolean("save", true).commit();
		} else if (login_ckb_auto.isChecked()) {
			this.localEditor.putString("uid", usrStr).commit();
			this.localEditor.putString("pwd", pwdStr).commit();
			this.localEditor.putBoolean("auto", true).commit();
		}
	}
	// http post way1 :
	private String getLoginResp(String usrStr, String pwdStr) {
		String usrNm = "";
		String XMLDATA = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<login>" + "<username>" + usrStr + "</username>" + "<password>" + pwdStr + "</password>" + "</login>";
		final String SERVER_URL = "http://59.46.197.188:7001/easd/mobileEntry.do"; 
		HttpPost httpRequest = new HttpPost(SERVER_URL);
		List params = new ArrayList();
		params.add(new BasicNameValuePair("type", "login")); 
		params.add(new BasicNameValuePair("data", XMLDATA)); 
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				// <?xml version="1.0" encoding="UTF-8" ?><response><message>OK,陈小蛟</message></response>
				String[] userinfo = strResult.split(",");
				int len = userinfo.length;
				if (userinfo[0].endsWith("OK")) {
					usrNm = userinfo[len - 1].substring(0, userinfo[len - 1].indexOf("</message>"));
				}
				Log.i(TAG, strResult);
			} else {
				Log.e(TAG, "Error Response" + httpResponse.getStatusLine().toString());
			}
		} catch (ClientProtocolException e) {
			Log.e(TAG, e.getMessage().toString());
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, e.getMessage().toString());
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(TAG, e.getMessage().toString());
			e.printStackTrace();
		}
		return usrNm;
	}
}
